package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.service.ApiAddressService;
import com.platform.service.ApiOrderService;
import com.platform.service.ApiProductService;
import com.platform.service.ApiShopService;
import com.platform.util.ApiBaseAction;
import com.platform.util.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanghao
 */
@Api(tags = "用户订单相关")
@RestController
@RequestMapping("/api/order")
@Slf4j
public class ApiOrderController extends ApiBaseAction {
    @Autowired
    private ApiOrderService orderService;
    @Autowired
    private ApiProductService productService;
    @Autowired
    private ApiShopService shopService;
    @Autowired
    private ApiAddressService addressService;

    /**
     * 创建用户购买订单
     */
    @ApiOperation(value = "创建用户购买订单")
    @PostMapping("create")
    public Object create(@LoginUser UserVo loginUser) {
        JSONObject json = this.getJsonRequest();
        log.info("创建订单入参为：{}", json.toJSONString());
        CreatWxuserOrderDto dto = JSONObject.toJavaObject(json, CreatWxuserOrderDto.class);

        //查询店铺信息
        ShopVo shopVo = shopService.queryById(dto.getShopId());
        log.info("店铺信息为：{}", shopVo.toString());

        //查询产品数据
        List<CreatWxuserOrderGoodsDto> goodList = dto.getGoodList();
        List<ProductVo> productVoList = new ArrayList<>();
        BigDecimal goods_price =  new BigDecimal("0");
        for (CreatWxuserOrderGoodsDto creatWxuserOrderGoodsDto : goodList) {
            ProductVo productVo = productService.queryProduct(creatWxuserOrderGoodsDto.getGoodId());
            //校验产品是否上架
            if(productVo.getStatus() == 1){
                return toResponsFail("商品暂无法出售");
            }
            //校验产品价格是否合法
            if ( productVo.getSale_price().compareTo(BigDecimal.ZERO) != 1) {
                return toResponsFail("商品异常");
            }
            //校验产品库存是否满足
            if (productVo.getStock_num() < creatWxuserOrderGoodsDto.getGoodNum()){
                return toResponsFail("商品库存不足");
            }
            goods_price = goods_price.add((productVo.getSale_price().multiply(new BigDecimal(creatWxuserOrderGoodsDto.getGoodNum()))));
            productVo.setNumber(creatWxuserOrderGoodsDto.getGoodNum());
            productVoList.add(productVo);
        }
        log.info("购买商品信息为：{}", productVoList.toString());
        //校验收货地址
        AddressVo addressVo = addressService.queryObject(dto.getAddressId());
        if (addressVo == null){
            return toResponsFail("收货地址不存在");
        }

        //创建订单
        dto.setUserName(addressVo.getUserName());
        dto.setBuildingId(addressVo.getBuildingId());
        dto.setBuildingName(addressVo.getBuildingName());
        dto.setDetailInfo(addressVo.getDetailInfo());
        dto.setRoom(addressVo.getRoom());
        dto.setSchoolId(addressVo.getSchoolId());
        dto.setSchoolName(addressVo.getSchoolName());
        dto.setTelNumber(addressVo.getTelNumber());

        dto.setUser_id(loginUser.getUserId().intValue());
        dto.setOrder_sn(CommonUtil.generateOrderNumber());
        dto.setGoods_price(goods_price);

        //订单总价：商品总价 >= 免费配送额度？商品总价：商品总价+配送费
        BigDecimal giveFree = new BigDecimal(shopVo.getGiveFree());
        dto.setOrder_price(goods_price.compareTo(giveFree) >= 0 ? goods_price : goods_price.add(new BigDecimal(shopVo.getGiveMoney())));


        dto.setActual_price(null);
        dto.setOrder_status(2);//订单状态为2:待支付
        dto.setTranfer_status(0);//提现状态为0:未提现
        dto.setPay_status(0);//支付状态为0:待支付
        dto.setPay_id("");
        dto.setPay_time(null);
        dto.setNote("");
        dto.setImage(productVoList.get(0).getPrimary_pic_url());
        dto.setShop_name(shopVo.getShopName());
        dto.setShop_logo(shopVo.getLogo());
        dto.setType(0);
        log.info("订单详情信息为：{}", dto.toString());

        //添加订单详情表
        int i = orderService.create(dto);
        if (i != 1){
            return toResponsFail("创建订单失败");
        }
        //添加订单商品关系表
        for (ProductVo productVo : productVoList) {
            CreateWxuserOrderGoodsDto dto1 = new CreateWxuserOrderGoodsDto();
            dto1.setOrder_sn(dto.getOrder_sn());
            dto1.setName(productVo.getName());
            dto1.setImage(productVo.getPrimary_pic_url());
            dto1.setProduct_id(productVo.getId());
            dto1.setNumber(productVo.getNumber());
            dto1.setSale_price(productVo.getSale_price());
            int j = orderService.createOrderGoods(dto1);
            if (j != 1){
                return toResponsFail("创建订单失败");
            }
        }

        return toResponsSuccess(dto.getOrder_sn());
    }

    /**
     * 获取订单列表
     */
    @ApiOperation(value = "获取订单列表")
    @PostMapping("list")
    public Object queryOrderList(@LoginUser UserVo loginUser) {
        Integer user_id = loginUser.getUserId().intValue();
        return toResponsSuccess(orderService.queryOrderList(user_id));
    }

    /**
     * 查询订单详情
     */
    @ApiOperation(value = "查询订单详情")
    @PostMapping("detail")
    public Object detail(@LoginUser UserVo loginUser) {
        JSONObject json = this.getJsonRequest();
        String order_sn = (String) json.get("order_sn");

        return toResponsSuccess(orderService.queryObjectByOrderSn(order_sn));
    }

    /**
     * 取消订单
     */
    @ApiOperation(value = "取消订单")
    @PostMapping("cancel")
    public Object cancel(@LoginUser UserVo loginUser) {
        JSONObject json = this.getJsonRequest();
        String order_sn = (String) json.get("order_sn");

        Integer user_id = loginUser.getUserId().intValue();
        return toResponsSuccess(orderService.cancel(order_sn,user_id));
    }

    /**
     * 查询商铺所有订单
     */
    @ApiOperation(value = "查询商铺所有订单")
    @PostMapping("queryAllOrderByShopId")
    public Object queryAllOrderByShopId(@LoginUser UserVo loginUser) {
        //查询登录用户的店铺
        Integer userId = loginUser.getUserId().intValue();
        ShopVo shopVo = shopService.queryByUserId(userId);
        //根据shopId查询所有订单
        return toResponsSuccess(orderService.queryAllOrderByShopId(shopVo.getShopId()));
    }

    /**
     * 商户取消订单
     */
    @ApiOperation(value = "商户取消订单")
    @PostMapping("shopCancel")
    public Object shopCancel(@LoginUser UserVo loginUser) {
        JSONObject json = this.getJsonRequest();
        String order_sn = (String) json.get("order_sn");

        Integer user_id = loginUser.getUserId().intValue();
        ShopVo shopVo = shopService.queryByUserId(user_id);
        return toResponsSuccess(orderService.shopCancel(order_sn,shopVo.getShopId()));
    }

}